package com.wuyou.controller;

import cn.hutool.json.JSONUtil;
import com.wuyou.domain.Result;
import com.wuyou.entity.TbContract;
import com.wuyou.entity.TbHouse;
import com.wuyou.entity.TbUser;
import com.wuyou.entity.TdHost;
import com.wuyou.service.ITbContractService;
import com.wuyou.service.ITbHouseService;
import com.wuyou.service.ITbUserService;
import com.wuyou.service.ITdHostService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yz
 * @since 2022-09-30
 */
@RestController
@RequestMapping("contract")
@Api(value = "订单接口文档")
public class TbContractController {

    @Autowired
    private ITbHouseService houseService;

    @Autowired
    private ITbUserService userService;

    @Autowired
    private ITdHostService hostService;

    @Autowired
    private ITbContractService contractService;

    @GetMapping
    @ApiOperation("根据ID查询数据")//这个注释是对当前这个接口的解释
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "path")
    public Result selectById(@RequestParam("userId") Long userId, @RequestParam("houseId") Long houseId ,TbContract contract){
        try {
            TbHouse house = houseService.selectById(houseId);
            //根据房屋的房主ID查询到此人
            BigDecimal rent = house.getRent();
            String s = JSONUtil.toJsonStr(rent.toString());
            String hostId = house.getHostId();


            TdHost host = hostService.selectById(hostId);
//            房东id
            Long hostId1 = host.getHostId();
            Long id = host.getUserId();
            TbUser tbUser = userService.selectById(id);
            //房东的姓名身份证号联系方式
            String userName1 = tbUser.getUserName();
            String cardID1 = tbUser.getCardID();
            String jiafang = tbUser.getUserPhone();


            TbUser user = userService.selectById(userId);
            //获取姓名传入doc中
            String userName = user.getUserName();
            String cardID = user.getCardID();
            String yifang = user.getUserPhone();

            //获取当前时间
            Date d = new Date();
            System.out.println(d);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(d);
            System.out.println("格式化后的日期：" + dateNowStr);

            //拼接传入模板
                Map<String, Object> map = new HashMap<>();
                map.put("jianame",userName1);
                map.put("yiname",userName);
                map.put("yue","12");
                map.put("dangqianshijian",dateNowStr);
                map.put("jieshushijian","2023-10-1");
                map.put("rmb",s);
                map.put("zhifufangshi","微信");
                map.put("jiashengfenzheng",cardID1);
                map.put("yishenfenzheng", cardID);
                map.put("jialianxifanshi", jiafang);
                map.put("yilianxifangshi", yifang);

                Configuration configuration = new Configuration();
                configuration.setDefaultEncoding("utf-8");
                //.xml 模板文件所在目录
                configuration.setDirectoryForTemplateLoading(new File("D:\\freemarker\\doc\\"));
                // 输出文档路径及名称租房
                File outFile = new File("D:\\freemarker\\doc\\" + UUID.randomUUID()+ ".doc");
                Template t =  configuration.getTemplate("租房合同.xml","utf-8");
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
                t.process(map, out);
                out.close();
                System.out.println("生成成功");


            //增加方法
            TbContract tbContract = new TbContract();
            tbContract.setHouseId(houseId);//house_id
            tbContract.setHostId(hostId1);
            tbContract.setUserId(userId);
            tbContract.setRent(rent);
            tbContract.setPayStatus(1);
            tbContract.setPayTime(d);
            tbContract.setStartTime(d);
            tbContract.setEndTime(d);

            contractService.addContract(tbContract);
            System.err.println("增加成功"+tbContract);
            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR();
        }
    }

    //平台受理 0未受理 1受理
    @PutMapping("/{contractId}")
    @ApiOperation("根据ID修改数据")//这个注释是对当前这个接口的解释
    @ApiImplicitParams({
            @ApiImplicitParam(name = "contractId", value = "合同ID", required = true, paramType = "body"),
            @ApiImplicitParam(name = "contract", value = "合同实体",required = true, paramType = "path")
    })
    public Result updateStatus(@PathVariable("contractId") Integer contractId , @RequestParam("contract")TbContract contract){
        try {
            contractService.updateStatus(contract);
            return Result.OK().setData("成功");
        }catch (Exception e){
            return Result.ERROR();
        }
    }


}
